<template>
    <div>
        <span v-html="md.render(displayedText)"></span>
    </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';

const props = defineProps({
    text: {
        type: String,
        required: true
    },
    speed: {
        type: Number,
        default: 1000
    },
    isStop: {
        type: Boolean,
        default: false
    },
    cursor: {
        type: Boolean,
        default: true
    }
});

const emit = defineEmits(['loadOver']);

const displayedText = ref('');
const cursorVisible = ref(true);

// Markdown 解析
const md = computed(() => {
    return new MarkdownIt({
        html: true,
        linkify: true,
        typographer: true,
        breaks: true,
        highlight: function (str, lang) {
            if (lang && hljs.getLanguage(lang)) {
                try {
                    return `<pre><code class="language-${lang} hljs">` +
                        hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                        '</code></pre>';
                } catch (__) {}
            }
            return '<pre><code class="language-none hljs">' + md.value.utils.escapeHtml(str) + '</code></pre>';
        }
    });
});

// 逐字输出文本
const typeText = async () => {
    for (let i = 0; i < props.text.length; i++) {
        displayedText.value += props.text[i];
        if (props.isStop) {
            break;
        }
        await sleep(props.speed);
    }
    emit('loadOver', { status: true, copytext: displayedText.value });
};

// 睡眠函数
const sleep = (ms) => {
    return new Promise(resolve => setTimeout(resolve, ms));
};

// 光标闪烁
const blinkCursor = () => {
    setInterval(() => {
        cursorVisible.value = !cursorVisible.value;
    }, 500);
};

// 组件挂载后执行
onMounted(() => {
    typeText();
    if (props.cursor) {
        blinkCursor();
    }
});
</script>
<style scoped>
/* 可自定义光标样式 */
</style>
